package com.lb.base.util;

import com.lb.api.ApiLogRequest;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

import static com.lb.base.constants.BaseConstants.*;
import static org.springframework.web.context.request.RequestAttributes.SCOPE_REQUEST;

/**
 * 请求相关工具类
 *
 * @author xiemingzhi
 * @since 1.0
 */
@Component
public class RequestUtils {

    public static String getTraceId(HttpServletRequest request) {
        String traceId = request.getHeader(REQUEST_HEADER_KEY_REQUEST_ID);
        if (!StringUtils.hasText(traceId)) {
            traceId = UUID.randomUUID().toString().replace("-", "");
        }
        return traceId;
    }

    @Nullable
    public static String getUserId() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            Object attribute = requestAttributes.getAttribute(REQUEST_ATTRIBUTE_KEY_API_USER_ID, SCOPE_REQUEST);
            if (attribute instanceof String) {
                return (String) attribute;
            }
        }
        return null;
    }

    @Nullable
    public static ApiLogRequest getApiLogRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            Object attribute = requestAttributes.getAttribute(REQUEST_ATTRIBUTE_KEY_API_LOG_REQUEST, SCOPE_REQUEST);
            if (attribute instanceof ApiLogRequest) {
                return (ApiLogRequest) attribute;
            }
        }
        return null;
    }

    public static Long getCurrentTimeMillis() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            Object attribute = requestAttributes.getAttribute(REQUEST_ATTRIBUTE_KEY_API_CURRENT_TIME_MILLIS, SCOPE_REQUEST);
            if (attribute instanceof Long) {
                return (Long) attribute;
            }
        }
        return System.currentTimeMillis();
    }
}
